package jmind.core.image.ocr;

import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import jmind.base.util.DataUtil;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;

/**
 * 条形码生成和解析
 * http://sjsky.iteye.com/blog/1142177
 * @author weibo-xie
 * 2012-8-8
 */
public class ZxingBarcode {

    /**
     * 生成条形码
     * @param contents 内容
     * @param width 宽度
     * @param height  高度
     * @param imgPath  图片路径
     */
    public static void encode(String contents, int width, int height, String imgPath) {
        int codeWidth = 3 + // start guard
                (7 * 6) + // left bars
                5 + // middle guard
                (7 * 6) + // right bars
                3; // end guard
        codeWidth = Math.max(codeWidth, width);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, codeWidth, height,
                    null);

            MatrixToImageWriter.writeToFile(bitMatrix, "png", new File(imgPath));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解码
     * @param imgPath 图片路径
     * @return String
     */
    public static String decode(String imgPath) {
        BufferedImage image = null;
        Result result = null;
        try {
            image = ImageIO.read(new File(imgPath));
            if (image == null) {
                System.out.println("the decode image may be not exit.");
            }
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            result = new MultiFormatReader().decode(bitmap, null);
            return result.getText();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return DataUtil.EMPTY;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        String imgPath = "d:/data/2901.jpg";
        // 益达无糖口香糖的条形码
        //        String contents = "6923450657713";
        //
        //        int width = 105, height = 50;

        //  handler.encode(contents, width, height, imgPath);
        String decode = ZxingBarcode.decode(imgPath);
        System.out.println(decode);
    }
}
